package de.projectgoodmorning.alarm;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import de.projectgoodmorning.alarm.R;

public class PlaySoundService extends Service implements OnPreparedListener {

	private MediaPlayer player = null;

//	@Override
//	public boolean onUnbind( Intent intent ) {
//		if( player == null ) {
//			stopSelf();
//		} else if( !player.isPlaying() ) {
//			stopSelf();
//		}
//		
//		return super.onUnbind( intent );
//	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();

		if( player != null ) {
			player.release();
		}
	}
	
	public void play( Uri uri ) {
		try {
			setupForUri( uri );
		} catch( Exception e ) {
			setupForFallback();
		}
	}
	
	private void setupForUri( Uri uri ) throws Exception {
		player = new MediaPlayer();
		player.setAudioStreamType( AudioManager.STREAM_MUSIC );
		player.setDataSource( getApplicationContext(), uri );
		player.setLooping( true );
		player.setOnPreparedListener( this );
		player.prepareAsync();
	}

	private void setupForFallback() {
		player = MediaPlayer.create( this, R.raw.church );
		player.setLooping( true );
		player.start();
	}

	public void onPrepared( MediaPlayer player ) {
		player.start();
	}
	
	public void stopPlayer() {
		player.stop();
	}

	
	/////////////////////// SERVICE ///////////////////////////
	
    public class LocalBinder extends Binder {
    	public PlaySoundService getService() {
            return PlaySoundService.this;
        }
    }		
	
	private final IBinder binder = new LocalBinder();
	@Override
	public IBinder onBind( Intent intent ) {
		return binder;
	}
}
